/*
 Copyright 2010 Victor Mayoral Vilches
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#import "TextFieldController.h"
#import "Constants.h"

#define kTextFieldWidth	260.0
#define kSliderHeight			10.0

#define kStdButtonWidth		106.0
#define kStdButtonHeight	40.0


static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

const NSInteger kViewTag = 1;

@implementation TextFieldController

@synthesize textFieldNormal, textFieldRounded, textFieldSecure, sliderAngleView, dataSourceArray;

- (void)dealloc
{
	[textFieldNormal release];
	[textFieldRounded release];
	[textFieldSecure release];
	[sliderAngleView release];
//    [botonEnvio release];
	
	[dataSourceArray release];
	
	[super dealloc];
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	
	self.dataSourceArray = [NSArray arrayWithObjects:
								[NSDictionary dictionaryWithObjectsAndKeys:
								 @"Direccion ip del servidor", kSectionTitleKey,
								 @"Introduzca la direccion ip del robot", kSourceKey,
								 self.textFieldNormal, kViewKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
								 @"Puerto del servidor", kSectionTitleKey,
								 @"Introduzca el puerto al cual está conectado el robot", kSourceKey,
								 self.textFieldRounded, kViewKey,
							 nil],
							
							[NSDictionary dictionaryWithObjectsAndKeys:
								 @"Contraseña", kSectionTitleKey,
								 @"Seguridad en el acceso al servicio", kSourceKey,
								 self.textFieldSecure, kViewKey,
							 nil],                            
							
							[NSMutableDictionary dictionaryWithObjectsAndKeys:
								 @"Ángulo de giro", kSectionTitleKey,
								 @"Angulo en grados que gira el robot", kSourceKey,
								 self.sliderAngleView, kViewKey,
								 nil],

//							[NSDictionary dictionaryWithObjectsAndKeys:
//                             @"Envio", kSectionTitleKey,
//                             @"Envia los parametros al servidor", kSourceKey,
//                             self.botonEnvio, kViewKey,
//                             nil],                                                        
                            
                            
							nil];
	
	self.title = NSLocalizedString(@"Configuracion", @"");
	
	// we aren't editing any fields yet, it will be in edit when the user touches an edit field
	self.editing = NO;    
}

// called after the view controller's view is released and set to nil.
// For example, a memory warning which causes the view to be purged. Not invoked as a result of -dealloc.
// So release any properties that are loaded in viewDidLoad or can be recreated lazily.
//
- (void)viewDidUnload
{
	[super viewDidUnload];
	
	// release the controls and set them nil in case they were ever created
	// note: we can't use "self.xxx = nil" since they are read only properties
	//
	[textFieldNormal release];
	textFieldNormal = nil;		
	[textFieldRounded release];
	textFieldRounded = nil;
	[textFieldSecure release];
	textFieldSecure = nil;
	[sliderAngleView release];
	sliderAngleView = nil;
//    [botonEnvio release];
//    botonEnvio = nil;
	
	self.dataSourceArray = nil;
}


#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [self.dataSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.dataSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 2;
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ([indexPath row] == 0) ? 40.0 : 20.0;
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = nil;
	NSUInteger row = [indexPath row];
	if (row == 0)
	{
		static NSString *kCellTextField_ID = @"CellTextField_ID";
		cell = [tableView dequeueReusableCellWithIdentifier:kCellTextField_ID];
		if (cell == nil)
		{
			// a new cell needs to be created
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellTextField_ID] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}
		else
		{
			// a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
			UIView *viewToCheck = nil;
			viewToCheck = [cell.contentView viewWithTag:kViewTag];
			if (!viewToCheck)
				[viewToCheck removeFromSuperview];
            UIView *vistaSecundaria =  [cell.contentView.subviews objectAtIndex:0];
            [vistaSecundaria removeFromSuperview];
		}
		
		UITextField *textField = [[self.dataSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
		[cell.contentView addSubview:textField];
	}
	else /* (row == 1) */
	{
		static NSString *kSourceCell_ID = @"SourceCell_ID";
		cell = [tableView dequeueReusableCellWithIdentifier:kSourceCell_ID];
		if (cell == nil)
		{
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kSourceCell_ID] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
            cell.textLabel.textAlignment = UITextAlignmentCenter;
            cell.textLabel.textColor = [UIColor grayColor];
			cell.textLabel.highlightedTextColor = [UIColor blackColor];
            cell.textLabel.font = [UIFont systemFontOfSize:10];
		}
		
		cell.textLabel.text = [[self.dataSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey];
	}
	
    return cell;
}


#pragma mark -
#pragma mark UITextFieldDelegate


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //Actualizamos las variables globales
    if (textField == textFieldNormal)
    {
        NSString *aux = [[NSString alloc]initWithString:textField.text];
        direccion_ip_host = aux;
        printf("El valor de la dirección ip del host es %s \n",aux);
        [self alertSimpleAction];

    }
    else if(textField == textFieldRounded)
    {
        NSString *aux = [[NSString alloc]initWithString:textField.text];
        puerto_host = aux;
        printf("El valor del puerto del host es %s \n",aux);
        [self alertSimpleAction];

    }
    else
    {
        NSLog(@"Error");
    }
    
    
    
	// the user pressed the "Done" button, so dismiss the keyboard	
    [textField resignFirstResponder];
	return YES;
    
}



#pragma mark -
#pragma mark Objects in the table

- (UITextField *)textFieldNormal
{
	if (textFieldNormal == nil)
	{
		CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
		textFieldNormal = [[UITextField alloc] initWithFrame:frame];
		
		textFieldNormal.borderStyle = UITextBorderStyleRoundedRect;
		textFieldNormal.textColor = [UIColor blackColor];
		textFieldNormal.font = [UIFont systemFontOfSize:17.0];
		textFieldNormal.placeholder = @"10.211.55.6";
		textFieldNormal.backgroundColor = [UIColor whiteColor];
		textFieldNormal.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
		
		textFieldNormal.keyboardType = UIKeyboardTypeDefault;
		textFieldNormal.returnKeyType = UIReturnKeyDone;
		
		textFieldNormal.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
		
		textFieldNormal.tag = kViewTag;		// tag this control so we can remove it later for recycled cells
		
		textFieldNormal.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
	}
	return textFieldNormal;
}

- (UITextField *)textFieldRounded
{
	if (textFieldRounded == nil)
	{
		CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
		textFieldRounded = [[UITextField alloc] initWithFrame:frame];
		
		textFieldRounded.borderStyle = UITextBorderStyleRoundedRect;
		textFieldRounded.textColor = [UIColor blackColor];
		textFieldRounded.font = [UIFont systemFontOfSize:17.0];
		textFieldRounded.placeholder = @"6000";
		textFieldRounded.backgroundColor = [UIColor whiteColor];
		textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
		
		textFieldRounded.keyboardType = UIKeyboardTypeDefault;
		textFieldRounded.returnKeyType = UIReturnKeyDone;
		
		textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
		
		textFieldRounded.tag = kViewTag;		// tag this control so we can remove it later for recycled cells
		
		textFieldRounded.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
	}
	return textFieldRounded;
}

- (UITextField *)textFieldSecure
{
	if (textFieldSecure == nil)
	{
		CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
		textFieldSecure = [[UITextField alloc] initWithFrame:frame];
		textFieldSecure.borderStyle = UITextBorderStyleBezel;
		textFieldSecure.textColor = [UIColor blackColor];
		textFieldSecure.font = [UIFont systemFontOfSize:17.0];
		textFieldSecure.placeholder = @"<enter password>";
		textFieldSecure.backgroundColor = [UIColor whiteColor];
		
		textFieldSecure.keyboardType = UIKeyboardTypeDefault;
		textFieldSecure.returnKeyType = UIReturnKeyDone;	
		textFieldSecure.secureTextEntry = YES;	// make the text entry secure (bullets)
		
		textFieldSecure.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
		
		textFieldSecure.tag = kViewTag;		// tag this control so we can remove it later for recycled cells
		
		textFieldSecure.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
	}
	return textFieldSecure;
}

//- (UITextField *)sliderAngleView
//{
//	if (sliderAngleView == nil)
//	{
//		CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
//		sliderAngleView = [[UITextField alloc] initWithFrame:frame];
//		sliderAngleView.borderStyle = UITextBorderStyleBezel;
//		sliderAngleView.textColor = [UIColor blackColor];
//		sliderAngleView.font = [UIFont systemFontOfSize:17.0];
//		sliderAngleView.placeholder = @"<enter text>";
//		sliderAngleView.backgroundColor = [UIColor whiteColor];
//		
//		sliderAngleView.keyboardType = UIKeyboardTypeDefault;
//		sliderAngleView.returnKeyType = UIReturnKeyDone;	
//		
//		sliderAngleView.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
//		
//		sliderAngleView.tag = kViewTag;		// tag this control so we can remove it later for recycled cells
//		
//		sliderAngleView.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"segment_check.png"]];
//		sliderAngleView.leftViewMode = UITextFieldViewModeAlways;
//		
//		sliderAngleView.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
//	}
//	return sliderAngleView;
//}

- (UISlider *)sliderAngleView
{
    if (sliderAngleView == nil) 
    {
        CGRect frame = CGRectMake(50.0, 12.0, 200.0, kSliderHeight);
        sliderAngleView = [[UISlider alloc] initWithFrame:frame];
        [sliderAngleView addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        
        // in case the parent view draws with a custom color or gradient, use a transparent color
        sliderAngleView.backgroundColor = [UIColor clearColor];
        
        sliderAngleView.minimumValue = 0.0;
        sliderAngleView.maximumValue = 360.0;
        sliderAngleView.continuous = YES;
        sliderAngleView.value = 180.0;
		
		sliderAngleView.tag = kViewTag;	// tag this view for later so we can remove it from recycled table cells
    }
    return sliderAngleView;
}


//- (UIButton *)botonEnvio
//{
//	if (botonEnvio == nil)
//	{
//		// create a UIButton (UIButtonTypeRoundedRect)
//		botonEnvio = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
//		botonEnvio.frame = CGRectMake(182.0, 5.0, kStdButtonWidth, kStdButtonHeight);
//		[botonEnvio setTitle:@"Rounded" forState:UIControlStateNormal];
//		botonEnvio.backgroundColor = [UIColor clearColor];
//		[botonEnvio addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//		
//		botonEnvio.tag = kViewTag;	// tag this view for later so we can remove it from recycled table cells
//	}
//	return botonEnvio;
//}


#pragma mark -
#pragma mark Actions

- (void)sliderAction:(id)sender
{
    NSMutableString *cadena = [[NSMutableString alloc] initWithString:@"Angulo en grados que gira el robot: "];
    [cadena appendString:[NSString stringWithFormat:@"%f",sliderAngleView.value]];
    NSLog(cadena);
    [[self.dataSourceArray objectAtIndex:3] setValue:cadena forKey:kSourceKey];
}

-(void)buttonAction:(id)sender
{
}

- (void)alertSimpleAction
{
    NSMutableString *aux = [[NSMutableString alloc] init];
    [aux appendString:@" Direccion ip: "];
    [aux appendString:direccion_ip_host];
    [aux appendString:@", puerto: "];
    [aux appendString:puerto_host];
    
	// open an alert with just an OK button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Servidor Cambiado" message: aux
                                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
	[alert show];	
	[alert release];
}

@end

